package com.nantong.admin.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantong.admin.domain.SysUser;
import com.nantong.admin.domain.model.request.user.SysUserSearch;
import com.nantong.admin.domain.model.response.user.SysUserVo;
import com.nantong.admin.mapper.SysUserMapper;
import com.nantong.admin.service.ISysUserService;
import com.nantong.common.core.utils.StringUtils;
import com.nantong.common.mybatis.core.page.PageQuery;
import com.nantong.common.mybatis.core.page.TableDataInfo;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.nantong.admin.domain.SysUserRole;
import com.nantong.admin.mapper.SysUserRoleMapper;

/**
 * 用户 业务层处理
 *
 * @author nantong
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private final SysUserMapper userMapper;
    private final SysUserRoleMapper userRoleMapper;

    @Override
    public SysUser selectUserByUserName(String userName) {
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getUserName, userName);
        return userMapper.selectOne(lqw);
    }

    @Override
    public TableDataInfo<SysUserVo> selectPageList(SysUserSearch search, PageQuery pageQuery) {
        Page<SysUserVo> page = baseMapper.selectPageList(pageQuery.build(), this.buildQueryWrapper(search));
        return TableDataInfo.build(page);
    }

    @Override
    public List<SysUserVo> searchList(SysUserSearch search) {
        Wrapper<SysUser> sysUserWrapper = this.buildQueryWrapper(search);
        return baseMapper.selectVoList(sysUserWrapper);
    }

    private Wrapper<SysUser> buildQueryWrapper(SysUserSearch user) {
        Map<String, Object> params = user.getParams();
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId())
                .like(StringUtils.isNotBlank(user.getUserName()), SysUser::getUserName, user.getUserName())
                .like(StringUtils.isNotBlank(user.getNickName()), SysUser::getNickName, user.getNickName())
                .eq(user.getStatus()!=null, SysUser::getStatus, user.getStatus())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), SysUser::getPhonenumber, user.getPhonenumber())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysUser::getCreateTime, params.get("beginTime"), params.get("endTime"));
        return wrapper;
    }

    @Override
    @Transactional
    public boolean updateUserWithRoles(SysUser user) {
        // 更新用户基本信息
        boolean updateResult = this.updateById(user);

        if (updateResult && user.getRoleIds() != null) {
            // 删除用户原有角色
            LambdaQueryWrapper<SysUserRole> userRoleWrapper = new LambdaQueryWrapper<>();
            userRoleWrapper.eq(SysUserRole::getUserId, user.getUserId());
            userRoleMapper.delete(userRoleWrapper);
            // 添加新角色
            if (!user.getRoleIds().isEmpty()) {
                List<SysUserRole> userRoleList = user.getRoleIds().stream()
                    .map(roleId -> {
                        SysUserRole userRole = new SysUserRole();
                        userRole.setUserId(user.getUserId());
                        userRole.setRoleId(roleId);
                        return userRole;
                    })
                    .collect(Collectors.toList());

                userRoleMapper.insertBatch(userRoleList);
            }
        }

        return updateResult;
    }

    @Override
    @Transactional
    public boolean saveUserWithRoles(SysUser user) {
        // 保存用户基本信息
        boolean saveResult = this.save(user);

        if (saveResult && user.getRoleIds() != null && !user.getRoleIds().isEmpty()) {
            // 添加用户角色
            List<SysUserRole> userRoleList = user.getRoleIds().stream()
                .map(roleId -> {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(roleId);
                    return userRole;
                })
                .collect(Collectors.toList());

            userRoleMapper.insertBatch(userRoleList);
        }

        return saveResult;
    }

    @Override
    public SysUser getUserWithRoles(Long userId) {
        // 获取用户基本信息
        SysUser user = this.getById(userId);
        if (user != null) {
            // 获取用户角色ID列表
            List<Long> roleIds = userRoleMapper.selectRoleIdsByUserId(userId);
            user.setRoleIds(roleIds);
        }
        return user;
    }

}
